package com.jacky.demo.func;

import android.support.v4.hardware.fingerprint.FingerprintManagerCompat;
import android.support.v4.os.CancellationSignal;
import android.view.View;
import android.widget.TextView;

import com.jacky.demo.BaseActivity;
import com.jacky.demo.R;
import com.jacky.demo.util.ViewUtils;
import com.jacky.log.Logger;

/**
 * Created by Administrator on 2017-06-26.
 */

public class FingerActivity extends BaseActivity implements View.OnClickListener {

    TextView mTipsView;
    android.support.v4.os.CancellationSignal mCancel;

    FingerprintManagerCompat mFingerManager;
    FingerprintManagerCompat.AuthenticationCallback mFingerCallBack =
            new FingerprintManagerCompat.AuthenticationCallback() {

        @Override
        public void onAuthenticationError(int errMsgId, CharSequence errString) {
            mTipsView.getEditableText().append(errMsgId + " " + errString).append("\n");
            Logger.e(errMsgId, errString);
        }

        @Override
        public void onAuthenticationHelp(int helpMsgId, CharSequence helpString) {
            mTipsView.getEditableText().append(helpMsgId + " " + helpString).append("\n");
            Logger.w(helpMsgId, helpString);
        }

        @Override
        public void onAuthenticationSucceeded(FingerprintManagerCompat.AuthenticationResult result) {
            mTipsView.getEditableText().append("authentication success\n");
            Logger.d("authentication success");
        }

        @Override
        public void onAuthenticationFailed() {
            mTipsView.getEditableText().append("authentication failed\n");
            Logger.i("authentication failed");
        }
    };

    @Override
    protected int getContentView() {
        return R.layout.finger_activity;
    }

    @Override
    protected void initCreate() {
        setTitle("指纹识别");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        findViewById(R.id.btn_input).setOnClickListener(this);
        mTipsView = ViewUtils.findView(this, R.id.tv_tips);
        mFingerManager = FingerprintManagerCompat.from(this);
    }

    @Override
    public void onClick(View view) {
        if (!mFingerManager.isHardwareDetected()) {
            showToast("您的手机不支持指纹识别功能");
            return;
        }
        if (!mFingerManager.hasEnrolledFingerprints()) {
            showToast("您还没有录入指纹, 请在设置界面录入至少一个指纹");
            return;
        }

        switch (view.getId()) {
            case R.id.btn_input :
                mTipsView.setText("请将您的手指放在指纹识别器上\n");
                mCancel = new CancellationSignal();
                mFingerManager.authenticate(null, 0, mCancel, mFingerCallBack, null);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(mCancel != null) {
            mCancel.cancel();
            mCancel = null;
        }
    }
}
